package tables

import (
	"fmt"
	"peilian-api/app/global/errors"
	"peilian-api/app/global/variable"
	"time"

	"gorm.io/gorm"
)

type Member struct { // 会员信息
	Model
	Uid             int64  `json:"uid" gorm:"type:bigint(20);unsigned;not null;default:0;comment:用户id"`
	Bid             string `json:"bid" gorm:"type:varchar(64);not null;default:\"\";comment:此次交易id"`
	Phone           string `json:"phone" gorm:"type:varchar(32);not null;default:\"\";comment:用户手机号"`
	Title           string `json:"title" gorm:"type:varchar(256);not null;default:\"\";comment:title名称"`
	MemberStartTime string `json:"member_start_time" gorm:"type:varchar(64);not null;default:\"\";comment:会员购买时间"`
	MemberExpire    string `json:"member_expire" gorm:"type:varchar(255);not null;default:\"\";comment:会员过期时间"`
}

func (m *Member) TableName() string {
	return "member"
}

// 创建交易
func (*Member) CreateMember(m Member) uint {
	d := variable.DB.MySQL.Create(&m)
	if d.RowsAffected == 0 {
		return 0
	}
	return m.ID
}

// 根据Uid获取会员信息
func (*Member) GetMemeberByUid(uid int64) (Member, error) {
	var m Member
	if err := variable.DB.MySQL.Where("uid=?", uid).Find(&m).Error; err != nil {
		return m, fmt.Errorf(errors.DatabaseMySqlOptionFail)
	}
	return m, nil
}

// 根据Uid获取会员信息
func (*Member) GetMemberInfoByUid(uid int64) (member Member, exists bool, err error) {
	d := variable.DB.MySQL.Where("uid = ?", uid).Find(&member)
	var flag bool = true
	if d.RowsAffected == 0 {
		flag = false
	}
	return member, flag, d.Error
}

// 更新交易信息 sel 要更新的字段
func (m *Member) UpdateMember(id uint, member Member, sel ...string) error {
	if len(sel) == 0 {
		d := variable.DB.MySQL.Model(m).Where("id = ?", id).Updates(&member)
		if d.RowsAffected == 0 {
			return d.Error
		}
	} else {
		d := variable.DB.MySQL.Model(m).Select(sel).Where("id = ?", id).Updates(&member)
		if d.RowsAffected == 0 {
			return d.Error
		}
	}
	return nil
}

// 根据交易单号id查询交易信息
func (*Member) GetMemberInfoByBid(bid string) (member Member, exists bool, err error) {
	d := variable.DB.MySQL.Where("bid = ?", bid).Find(&member)
	var flag bool = true
	if d.RowsAffected == 0 {
		flag = false
	}
	return member, flag, d.Error
}

// 根据会员id更新失效
func (*Member) DeleteMemberInfoById(id int64) error {
	var member Member
	member.DeletedAt = gorm.DeletedAt{time.Now(), true}
	d := variable.DB.MySQL.Model(&member).Select("deleted_at").Where("id = ?", id).Updates(&member).Limit(1)
	return d.Error
}
